package com.lb.shopguide.ui.fragment.boss.market;

import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterActivityApply;
import com.lb.shopguide.adapter.AdapterMyActivity;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.market.ActivityApplyBean;
import com.lb.shopguide.entity.market.MyActivityBean;
import com.lb.shopguide.event.boss.RefreshMyActivityEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class FragmentMarketMyActivity extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerViewApply)
    RecyclerView mRecyclerViewApply;
    @BindView(R.id.recyclerViewMyActivity)
    RecyclerView mRecyclerViewMyActivity;
    @BindView(R.id.tv_history_apply)
    TextView tvHistoryApply;

    private ArrayList<ActivityApplyBean> mActivityApplyBeanList;
    private ArrayList<MyActivityBean> mMyActivityBeanList;

    private AdapterActivityApply mAdapterActivityApply;
    private AdapterMyActivity mAdapterMyActivity;

    private boolean empty2 = false;
    private View noDataView2;


    public static FragmentMarketMyActivity newInstance() {
        return new FragmentMarketMyActivity();
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_market_my_activity;
    }

    @Override
    public void initData() {
        mActivityApplyBeanList = new ArrayList<>();
        mMyActivityBeanList = new ArrayList<>();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));

        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_apply, (ViewGroup) mRecyclerViewApply.getParent(), false);
        TextView tvEmptyText = noDataView.findViewById(R.id.tv_text_no_view);
        tvEmptyText.setText("暂无未处理活动申请消息");

        noDataView2 = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_apply, (ViewGroup) mRecyclerViewApply.getParent(), false);
        TextView tvEmptyText2 = noDataView2.findViewById(R.id.tv_text_no_view);
        tvEmptyText2.setText("暂无我的活动");

        mRecyclerViewApply.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapterActivityApply = new AdapterActivityApply(R.layout.item_activity_apply, mActivityApplyBeanList, false);
        mRecyclerViewApply.setAdapter(mAdapterActivityApply);


        mRecyclerViewMyActivity.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapterMyActivity = new AdapterMyActivity(R.layout.item_my_activity, mMyActivityBeanList);
        mRecyclerViewMyActivity.setAdapter(mAdapterMyActivity);
        initRequest();
        initListener();
    }

    private void initListener() {
        mAdapterActivityApply.setOnCheckClickListener(new AdapterActivityApply.OnCheckClickListener() {
            @Override
            public void onChecked(String applyCode) {
                ((FragmentMarketing) getParentFragment()).start(FragmentActivityApply.newInstance(applyCode,null));
            }
        });
        mAdapterMyActivity.setOnDetailClickListener(new AdapterMyActivity.OnDetailClickListener() {
            @Override
            public void onDetailClick(String applyCode, String picUrl) {
                ((FragmentMarketing) getParentFragment()).start(FragmentActivityIntroduce.newInstance(picUrl));
            }
        });
    }

    @Override
    public void finishRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void sessionOutOfDate() {

    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    private void initRequest() {
        sendRequestGetActivityApplys();
        sendRequestGetGetMyActivity();
    }

    @Override
    public String getPageTag() {
        return FragmentMarketMyActivity.class.getName();
    }

    @Override
    public void onRefresh() {
        onRefreshMyActivity();
        onRefreshApply();
    }

    private void onRefreshApply() {
        mAdapterActivityApply.setEnableLoadMore(false);
        if (mError) {
            mAdapterActivityApply.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapterActivityApply.setEmptyView(noDataView);
                mNoData = false;
            } else {
                refreshApply();
            }
        }
    }

    private void onRefreshMyActivity() {
        mAdapterMyActivity.setEnableLoadMore(false);
        if (mError) {
            mAdapterMyActivity.setEmptyView(errorView);
            mError = false;
        } else {
            if (empty2) {
                mAdapterMyActivity.setEmptyView(noDataView2);
                empty2 = false;
            } else {
                refreshMyActivity();
            }
        }
    }

    public void refreshApply() {
        mActivityApplyBeanList = new ArrayList<>();
        sendRequestGetActivityApplys();
    }

    private void refreshMyActivity() {
        mMyActivityBeanList = new ArrayList<>();
        sendRequestGetGetMyActivity();
    }

    private void bindEmptyApply() {
        mActivityApplyBeanList.clear();
        mAdapterActivityApply.setNewData(mActivityApplyBeanList);
        mNoData = true;
        onRefreshApply();
    }

    private void bindEmptyMyActivity() {
        mMyActivityBeanList.clear();
        mAdapterMyActivity.setNewData(mMyActivityBeanList);
        empty2 = true;
        onRefreshMyActivity();
    }

    private void sendRequestGetActivityApplys() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    if (response.getReturnContent() != null) {
                        JsonArray jsonArrayActivityAdvices = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                        if (jsonArrayActivityAdvices.size() != 0) {
                            for (JsonElement obj : jsonArrayActivityAdvices) {
                                ActivityApplyBean bean = JsonUtil.getGson().fromJson(obj, ActivityApplyBean.class);
                                mActivityApplyBeanList.add(bean);
                            }
                            mAdapterActivityApply.setNewData(mActivityApplyBeanList);
                        } else {
                            bindEmptyApply();
                        }
                        finishRefresh();
                    }
                }
            }
        };
        ApiMethodBoss.listActivityApplication(new SimpleLbObserver(listener, otherListener), AppConstant.ACTIVITY_APPLYS, this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetGetMyActivity() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    if (response.getReturnContent() != null) {
                        JsonArray jsonArrayActivityAdvices = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                        if (jsonArrayActivityAdvices.size() != 0) {
                            for (JsonElement obj : jsonArrayActivityAdvices) {
                                MyActivityBean bean = JsonUtil.getGson().fromJson(obj, MyActivityBean.class);
                                mMyActivityBeanList.add(bean);
                            }
                            mAdapterMyActivity.setNewData(mMyActivityBeanList);
                        } else {
                            bindEmptyMyActivity();
                        }
                        finishRefresh();
                    }
                }
            }
        };
        ApiMethodBoss.listMyActivity(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    @OnClick(R.id.tv_history_apply)
    void gotoHistory() {
        ((FragmentMarketing) getParentFragment()).start(FragmentHistoryApply.newInstance());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void jumpActivity(RefreshMyActivityEvent event) {
        onRefresh();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}